<?php
namespace app\admin\controller;

use think\facade\Db;

class Merchant extends \app\BaseController
{
    /**
     * 商户列表页
     */
    public function index()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        // 获取查询参数
        $status = $this->request->param('status', '');
        $keyword = $this->request->param('keyword', '');
        $type = $this->request->param('type', '');
        $page = $this->request->param('page', 1);
        $limit = 15;
        
        // 构建查询条件
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        if (!empty($keyword)) {
            $where[] = ['merchant_name|store_name|legal_person|mobile|id_card_number', 'like', '%' . $keyword . '%'];
        }
        if ($type !== '') {
            $where[] = ['type', '=', $type];
        }
        
        try {
            // 获取商户列表
            $merchants = Db::name('merchant')
                          ->where($where)
                          ->order('create_time', 'desc')
                          ->paginate([
                              'list_rows' => $limit,
                              'page' => $page
                          ]);
            
            // 获取统计数据
            $statistics = [
                'total' => Db::name('merchant')->count(),
                'pending' => Db::name('merchant')->where('status', 2)->count(), // 已提交
                'approved' => Db::name('merchant')->where('status', 0)->count(), // 成功
                'rejected' => Db::name('merchant')->where('status', 4)->count(), // 已驳回
                'individual' => Db::name('merchant')->where('type', 4)->count(), // 个体工商户
                'enterprise' => Db::name('merchant')->where('type', 2)->count(), // 企业
            ];
            
        } catch (\Exception $e) {
            $merchants = [];
            $statistics = [
                'total' => 0,
                'pending' => 0,
                'approved' => 0,
                'rejected' => 0,
                'individual' => 0,
                'enterprise' => 0,
            ];
        }
        
        // 准备视图数据
        $data = [
            'title' => '商户列表',
            'current_menu' => 'merchant',
            'merchants' => $merchants,
            'statistics' => $statistics,
            'status' => $status,
            'keyword' => $keyword,
            'type' => $type,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('merchant/index', $data);
    }
    
    /**
     * 商户详情页
     */
    public function detail()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        $id = $this->request->param('id');
        
        try {
            $merchant = Db::name('merchant')->find($id);
            if (!$merchant) {
                return redirect('/admin/merchant')->with('error', '商户不存在');
            }
            if ($merchant['status'] == 4){
                $info = '';
                $reason = json_decode($merchant['reason'], true);
                foreach ($reason as $k => $v){
                    $info .=  $v['reject_reason']?? '' . "<br/>";
                }
                $merchant['reason'] = $info;
            }
        } catch (\Exception $e) {
            return redirect('/admin/merchant')->with('error', '查询失败');
        }
        
        // 准备视图数据
        $data = [
            'title' => '商户详情',
            'current_menu' => 'merchant',
            'merchant' => $merchant,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('merchant/detail', $data);
    }
    
    /**
     * 审核通过
     */
    public function approve()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->param('id');
        $remark = $this->request->post('remark', '');
        
        try {
            $merchant = Db::name('merchant')->find($id);
            if (!$merchant) {
                return json(['code' => 0, 'msg' => '商户不存在']);
            }
            
            Db::name('merchant')->where('id', $id)->update([
                'status' => 0, // 成功
                'remark' => $remark,
                'update_time' => time()
            ]);
            
            // 记录操作日志
            $this->addLog('approve_merchant', "审核通过商户：{$merchant['merchant_name']}", $id);
            
            return json(['code' => 1, 'msg' => '审核通过成功']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '操作失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 审核拒绝
     */
    public function reject()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->param('id');
        $reason = $this->request->post('reason', '');
        
        if (empty($reason)) {
            return json(['code' => 0, 'msg' => '请填写拒绝原因']);
        }
        
        try {
            $merchant = Db::name('merchant')->find($id);
            if (!$merchant) {
                return json(['code' => 0, 'msg' => '商户不存在']);
            }
            
            Db::name('merchant')->where('id', $id)->update([
                'status' => 4, // 已驳回
                'reason' => $reason,
                'update_time' => time()
            ]);
            
            // 记录操作日志
            $this->addLog('reject_merchant', "审核拒绝商户：{$merchant['merchant_name']}，原因：{$reason}", $id);
            
            return json(['code' => 1, 'msg' => '审核拒绝成功']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '操作失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除商户
     */
    public function delete()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->param('id');
        
        try {
            $merchant = Db::name('merchant')->find($id);
            if (!$merchant) {
                return json(['code' => 0, 'msg' => '商户不存在']);
            }
            
            $merchantName = $merchant['merchant_name'];
            Db::name('merchant')->delete($id);
            
            // 记录操作日志
            $this->addLog('delete_merchant', "删除商户：{$merchantName}", $id);
            
            return json(['code' => 1, 'msg' => '删除成功']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取状态文本
     */
    public static function getStatusText($status)
    {
        $statusMap = [
            1 => '填写中',
            2 => '已提交',
            3 => '代签约',
            4 => '已驳回',
            5 => '待打款',
            0 => '成功'
        ];
        
        return $statusMap[$status] ?? '未知';
    }
    
    /**
     * 获取类型文本
     */
    public static function getTypeText($type)
    {
        $typeMap = [
            2 => '企业',
            4 => '个体工商户'
        ];
        
        return $typeMap[$type] ?? '未知';
    }
    
    /**
     * 记录操作日志
     */
    private function addLog($action, $description, $target_id = 0)
    {
        try {
            $adminUser = $_SESSION['admin_user'];
            Db::name('admin_log')->insert([
                'admin_id' => $adminUser['id'],
                'admin_name' => $adminUser['username'],
                'action' => $action,
                'description' => $description,
                'target_id' => $target_id,
                'ip' => $this->request->ip(),
                'user_agent' => $this->request->header('User-Agent'),
                'create_time' => time()
            ]);
        } catch (\Exception $e) {
            // 日志记录失败不影响主要功能
        }
    }
}
